package com.gaojinqi.sys.modular.rbac.dao;

import com.gaojinqi.base.core.jpa.BaseRepository;
import com.gaojinqi.sys.modular.rbac.model.Permission;
import com.gaojinqi.sys.modular.rbac.model.RolePermissionMapping;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.List;

/**
 * 角色-权限 - 数据访问层接口
 *
 * @author gaojinqi
 * @version 1.0
 * @since 2020年04月21日
 */
@Repository
public interface RolePermissionRepository extends BaseRepository<RolePermissionMapping, String> {

    @Query("select rpm.perm from RolePermissionMapping rpm" +
            " where rpm.role.roleId = :roleId order by rpm.perm.sort asc ")
    List<Permission> findPermsByRoleId(@Param("roleId") String roleId);

    @Query("select rpm.perm from RolePermissionMapping rpm" +
            " where rpm.role.roleId = :roleId and rpm.perm.state = :state order by rpm.perm.sort asc ")
    List<Permission> findPermsByRoleIdAndState(
            @Param("roleId") String roleId, @Param("state") Byte state);

    @Query("select distinct (rpm.perm) from RolePermissionMapping rpm" +
            " where rpm.role.roleId in (:roleIds) and rpm.perm.state = :state order by rpm.perm.sort asc ")
    List<Permission> findPermsByRoleIdsAndState(
            @Param("roleIds") Collection<String> roleIds, @Param("state") Byte state);

    @Query("select distinct (rpm.perm) from RolePermissionMapping rpm, UserRoleMapping urm" +
            " where rpm.role.roleId = urm.role.role" +
            " and urm.user.userName = :userName and rpm.perm.state = :state order by rpm.perm.sort asc ")
    List<RolePermissionMapping> findRolePermsByUserNameAndState(
            @Param("userName") String userName, @Param("state") Byte state);

    @Query("select rpm from RolePermissionMapping rpm" +
            " where rpm.perm.url is not null and rpm.perm.state = :state order by rpm.perm.sort asc ")
    List<RolePermissionMapping> findRolePermsByState(@Param("state") Byte state);

    @Modifying
    @Query("delete from RolePermissionMapping rpm where rpm.role.roleId = :roleId")
    void deleteByRoleId(@Param("roleId") String roleId);

    @Modifying
    @Query("delete from RolePermissionMapping rpm where rpm.role.roleId in (:roleIds)")
    void deleteByRoleIds(@Param("roleIds") Collection<String> roleIds);

    @Modifying
    @Query("delete from RolePermissionMapping rpm where rpm.perm.permissionId = :permId")
    void deleteByPermId(@Param("permId") String permId);

    @Modifying
    @Query("delete from RolePermissionMapping rpm where rpm.perm.permissionId in (:permIds)")
    void deleteByPermId(@Param("permIds") Collection<String> permIds);

}
